package ua.kharkov.knure.pereverziev.diploma.util.email;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailSender {

	final static String EMAIL_ADRESS = "robot.tickbooking@gmail.com";
	private final static String EMAIL_HOST = "smtp.gmail.com";
	final static String EMAIL_PASSWORD = "robot123456";

	public static void send(final String address, final String subjectString,
			final String plainTextBody) throws MessagingException {

		final Properties properties = new Properties();
		properties.put("mail.smtp.host", EMAIL_HOST);
		properties.put("mail.password", EMAIL_PASSWORD);
		properties.put("mail.transport.protocol", "smtp");
		properties.put("mail.smtp.port", 587);
		properties.put("mail.smtp.auth", "true");

		properties.put("mail.smtp.starttls.enable", "true");
		// Use the following if you need SSL
		properties.put("mail.smtp.socketFactory.port", 465);
		properties.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.put("mail.smtp.socketFactory.fallback", "false");

		final Authenticator auth = new SMTPAuthenticator();
		final Session mailSession = Session
				.getDefaultInstance(properties, auth);

		// mailSession = Session.getInstance(properties);
		mailSession.setDebug(false);

		// create the Message
		final MimeMessage message = new MimeMessage(mailSession);
		final InternetAddress fromAddress = new InternetAddress(EMAIL_ADRESS);
		message.setFrom(fromAddress);
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(address));
		message.setSubject(subjectString);
		message.setText(plainTextBody);
		message.saveChanges();

		final Transport transport = mailSession.getTransport();
		transport.connect();
		transport.sendMessage(message,
				message.getRecipients(Message.RecipientType.TO));
		transport.close();
	}
}

class SMTPAuthenticator extends javax.mail.Authenticator {

	@Override
	public PasswordAuthentication getPasswordAuthentication() {
		final String username = EmailSender.EMAIL_ADRESS;
		final String password = EmailSender.EMAIL_PASSWORD;
		return new PasswordAuthentication(username, password);
	}
}